//
//  SWTableViewCell+PP.m
//  pickpic
//
//  Created by Jinxiao on 10/13/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "SWTableViewCell+PP.h"

@interface SWTableViewCell (PP_)
@property (readwrite, nonatomic, strong) UIControl *control;
@end

@implementation SWTableViewCell (PP)

- (UIControl *)control {
    UIControl *control = objc_getAssociatedObject(self, "control");
    if(control == nil) {
        control = [[UIControl alloc] init];
        objc_setAssociatedObject(self, "control", control, OBJC_ASSOCIATION_RETAIN);
    }
    return control;
}

+ (void)load {
    [self swizzleMethod:NSSelectorFromString(@"initializer") withMethod:@selector(swizzled_initializer) error:nil];
    [self swizzleMethod:NSSelectorFromString(@"layoutSubviews") withMethod:@selector(swizzled_layoutSubviews) error:nil];
}

- (void)swizzled_layoutSubviews {
    [self swizzled_layoutSubviews];

    UIView *view = self.contentView;

    self.control.frame = view.bounds;
}

- (void)swizzled_initializer {
    [self swizzled_initializer];

    self.exclusiveTouch = YES;
    self.multipleTouchEnabled = NO;

    UIView *view = self.contentView;

    [view insertSubview:self.control atIndex:0];

    self.control.backgroundColor = [UIColor clearColor];


    [self.control addTarget:self action:@selector(didFocusOn) forControlEvents:UIControlEventTouchDown|UIControlEventTouchDragEnter];
    [self.control addTarget:self action:@selector(didFocusOff) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchDragExit|UIControlEventTouchCancel];
    [self.control addTarget:self action:@selector(didSelect) forControlEvents:UIControlEventTouchUpInside];
//    UIView *view = [self valueForKey:@"cellScrollView"];
//    view.exclusiveTouch = YES;
//    view.multipleTouchEnabled = NO;
//
    UIGestureRecognizer *tgr = [self valueForKey:@"tapGestureRecognizer"];
    [tgr.view removeGestureRecognizer:tgr];

    UIGestureRecognizer *lgr = [self valueForKey:@"longPressGestureRecognizer"];
    [lgr.view removeGestureRecognizer:lgr];
}

- (void)didFocusOn
{
    [self setHighlighted:YES animated:NO];
}

- (void)didFocusOff
{
    [self setHighlighted:NO animated:NO];
}

- (void)didSelect {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    UIGestureRecognizer *tgr = [self valueForKey:@"tapGestureRecognizer"];
    [self performSelector:@selector(scrollViewTapped:) withObject:tgr];
#pragma clang diagnostic pop
}

@end
